<template>
  <div class="rolesBox">
    <el-breadcrumb separator-class="el-icon-caret-right">
      <el-breadcrumb-item :to="{ path: '/roles' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles' }">角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!--添加用户按钮 -->
      <el-row type="flex">
        <el-col :span="16">
          <el-row type="flex">
            <el-col :span="24">
              <el-button
                type="primary"
                @click="AdddialogFormVisible = true"
                class="btnl"
                >添加角色</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!-- 用户列表-->
      <el-table :data="tableData" border style="width: 100%  margin-top:10px">
        <el-table-column prop="id" type="expand" width="50">
          <template slot-scope="props">
            <!-- <span>{{ props.row }}</span> -->
            <!-- 第一层 -->
            <el-row v-for="(first, i) in props.row.children" :key="i">
              <el-col :span="4">
                <el-tag
                  closable
                  effect="dark"
                  @close="handleClose(first, props.row)"
                  >{{ first.authName }}</el-tag
                >
                <i class="el-icon-caret-right" v-if="first.children"></i>
              </el-col>
              <el-col :span="20">
                <!-- 第二层 -->
                <el-row v-for="(second, j) in first.children" :key="j">
                  <el-col :span="6">
                    <el-tag
                      closable
                      effect="dark"
                      type="success"
                      @close="handleClose(second, props.row)"
                      >{{ second.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right" v-if="second.children"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 第三层 -->
                    <el-tag
                      closable
                      effect="dark"
                      type="warning"
                      v-for="(three, k) in second.children"
                      :key="k"
                      @close="handleClose(three, props.row)"
                      >{{ three.authName }}
                      <i class="el-icon-caret-right" v-if="three.children"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row v-if="props.row.children.length === 0">
              <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- "id": 30,
            "roleName": "主管",
            "roleDesc": "技术负责人", -->
        <el-table-column prop="id" label="#" width="50" align="center">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center">
        </el-table-column>
        <!-- prop="mg_state" -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              icon="el-icon-delete"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                size="mini"
                type="warning"
                @click="allocatedLimits(scope.$index, scope.row)"
                icon="el-icon-s-tools"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog title="添加用户" :visible.sync="AdddialogFormVisible">
      <el-form :model="addform" ref="form" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="addform.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="addform.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="AdddialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色授权弹框 -->
    <el-dialog title="授权角色" :visible.sync="LimitsdialogFormVisible">
      <div class="tree-container">
        <el-tree
          :data="rightsData"
          highlight-current
          show-checkbox
          node-key="id"
          default-expand-all
          ref="tree"
          :default-checked-keys="selectRights"
          :props="defaultProps"
          @check-change="selectCheckEvent"
        >
        </el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="LimitsdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEmpower">确 定</el-button>
      </span>
    </el-dialog>
    <!--  编辑用户弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editform" ref="editform" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editform.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editform.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">编辑确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRights,
  getRoles,
  getDeleteRolesRights,
  getRolesRights,
  getAddRoles,
  getDeleteRoles,
  getQueryRolesById,
  getEditRoles,
} from "../../api/index";
export default {
  data() {
    return {
      tableData: [],
      LimitsdialogFormVisible: false, //定义权限弹框默认为不打开
      rightsData: [], //权限树数据
      selectRights: [], //初始化选中的角色授权
      defaultProps: {
        children: "children",
        label: "authName",
      },
      // 定义添加弹框数据
      AdddialogFormVisible: false,
      addform: {
        roleName: "",
        roleDesc: "",
      },
      formLabelWidth: "200px",
      // 验证规则
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      // 定义编辑弹框数据
      editDialogFormVisible: false,
      editform: {
        roleName: "",
        roleDesc: "",
      },
      // 定义角色id
      roleId: "",
      // 定义权限id
      rid: "",
    };
  },
  created() {
    this.initGetRoles();
  },
  methods: {
    // 初始化获取角色列表信息
    async initGetRoles() {
      let {
        data,
        meta: { status },
      } = await getRoles();
      if (status != 200) return this.$message.error("请求失败");
      this.tableData = data;
    },
    // 点击关闭tag事件删除权限
    async handleClose(tag, scopedRow) {
      let isFlag = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});
      if (!isFlag)
        return this.$message.info({
          message: "已取消删除",
        });
      console.log(tag); //权限id
      console.log(scopedRow); //当前行
      let {
        data,
        meta: { status },
      } = await getDeleteRolesRights({ roleId: scopedRow.id, rightId: tag.id });
      if (status != 200) return this.$message.error("删除授权失败");
      this.$message.success("删除授权成功");
      scopedRow.children = data;
    },
    // 角色授权
    async allocatedLimits(i, scopedRow) {
      // 每次打开唐狂的时候需要清除之前已经授权的id(第三级id)
      this.selectRights = [];
      this.roleId = scopedRow.id;
      // 1.弹框打开
      this.LimitsdialogFormVisible = true;
      // 2.数据展示
      let {
        data,
        meta: { status },
      } = await getRights({ type: "tree" });
      if (status != 200) return this.$message.error("请求失败");
      this.rightsData = data;
      // 获取到当前的用户
      console.log(scopedRow);
      this.checkNodeId(scopedRow, this.selectRights);
    },
    // 采用递归获取第三级权限选中的授权id
    checkNodeId(scopedRowNode, selectRightsArr) {
      // 最终节点没有children，判定为第三级权限
      if (!scopedRowNode.children) {
        return this.selectRights.push(scopedRowNode.id);
      }
      // 表示有children
      scopedRowNode.children.forEach((item) => {
        return this.checkNodeId(item, selectRightsArr);
      });
    },
    // 获取节点的状态
    selectCheckEvent() {
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      let HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      let arr = [...checkedKeys, ...HalfCheckedKeys];
      this.rid = arr.join(); //获取rid
      console.log(this.rid);
    },
    // 点击确定提交授权
    async submitEmpower() {
      let {
        meta: { status },
      } = await getRolesRights({ roleId: this.roleId, rids: this.rid });
      if (status != 200) return this.$message.error("授权失败");
      this.$message.success("授权成功！");
      this.LimitsdialogFormVisible = false;
      this.initGetRoles();
    },

    // 添加角色
    async addRoles() {
      let success = await this.$refs["form"].validate().catch(() => {});
      console.log(success);
      if (!success) return false;
      let {
        meta: { status },
      } = await getAddRoles(this.addform);
      if (status == 201) {
        this.$message.success("添加用户成功");
        this.AdddialogFormVisible = false;
        this.initGetRoles();
      }
    },
    // 删除角色
    async handleDelete(index, item) {
      let res = await this.$confirm("你确定要永久删除该文件吗？是否继续", {
        comfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (res != "confirm") return this.$message.info("取消删除");
      let {
        meta: { status, msg },
      } = await getDeleteRoles({ id: item.id });
      if (status == 200) {
        this.$message.success("删除成功");
        this.initGetRoles();
      } else {
        this.$message.error("删除失败");
      }
    },
    // 编辑角色
    async handleEdit(index, item) {
      // console.log(item)
      // 通过item.id查询到的数据
      let res = await getQueryRolesById({ id: item.id });
      let {
        data,
        meta: { status },
      } = res;
      if (status != 200) return this.$message.info("编辑失败");
      this.editform = data;
      // this.roleId =data.roleId;
      //将查询到的item.id添加到editform里面
      this.editform.id = item.id;
      // console.log( this.roleId);
      this.editDialogFormVisible = true;
    },
    // 真正编辑角色
    async editRoles() {
      let {
        meta: { status },
      } = await getEditRoles(this.editform);

      if (status != 200) return this.$message.info("编辑失败了");
      this.$message.success("编辑成功！");
      this.editDialogFormVisible = false;
      this.initGetRoles();
    },
  },
};
</script>

<style scoped>
.box-card {
  width: 1600px;
}
.rolesBox {
  padding-left: 20px;
}
.el-row {
  padding-left: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-breadcrumb {
  background-color: #fff;
  padding-left: 20px;
}
.el-tag {
  margin-right: 5px;
  margin-bottom: 20px;
}
.btnl {
  margin-left: -20px;
}
</style>